package com.tenchael.iblog.web.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by tenchael on 25/12/2017.
 */
abstract public class BaseController {

	private final Logger logger = LogManager.getLogger(getClass());

	@Autowired
	protected HttpServletRequest servRequest;

	@Autowired
	protected HttpServletResponse servResponse;

	@ExceptionHandler({Exception.class})
	public void handleException(Exception exception) {
		PrintWriter writer = null;
		try {
			logger.error("controller have error", exception);
			servResponse.setCharacterEncoding("UTF-8");
			writer = servResponse.getWriter();
			writer.println(exception.getMessage());
			writer.flush();
		} catch (IOException e) {
			logger.error("get writer from response occurs error", e);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}
}
